package com.google.p2pbench;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

public class Util {

  public static void assertOnThread(Handler handler) {
    assert handler.getLooper() == Looper.myLooper();
  }

  public static InetAddress getIpAddress() {
    try {
      List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
      for (NetworkInterface intf : interfaces) {
        List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
        for (InetAddress addr : addrs) {
          if (addr.isLoopbackAddress()) continue;
          if (!(addr instanceof Inet4Address)) continue;
          return addr;
        }
      }
    } catch (Exception e) {
    }
    return null;
  }

  public static float getBatteryLevel(Context context) {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = context.registerReceiver(null, ifilter);
    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    return level / (float)scale;
  }

  public static void recordToFile(File file, String line) {
    Log.w(MainActivity.TAG, "Recording " + line + " to " + file);
    try {
      FileWriter writer = new FileWriter(file, true);
      writer.write(line);
      writer.flush();
      writer.close();
    } catch (FileNotFoundException e) {
      Log.e(MainActivity.TAG, "File not found?", e);
    } catch (IOException e) {
      Log.e(MainActivity.TAG, "Could not record to file", e);
    }
  }

  public static String popFirstLine(File file) {
    try {
      BufferedReader reader = new BufferedReader(new FileReader(file));
      String firstLine = reader.readLine();
      BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
      String line;
      while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.newLine();
      }
      reader.close();
      writer.close();
      return firstLine;
    } catch (IOException e) {
      Log.e(MainActivity.TAG, "Failed to parse file", e);
    }
    return null;
  }
}
